﻿namespace DataIntegration.Deamon
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Reflection;
    using Castle.Windsor;
    using Castle.Windsor.Configuration.Interpreters;
    using Entities;
    using log4net;
    using log4net.Config;
    using Triggers.Manual;

    public class Daemon
    {
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().ReflectedType);

        private static List<IBrokerComponent> components;

        public static void Main()
        {
            XmlConfigurator.Configure();
            string daemonName = ConfigurationManager.AppSettings["name"];

            Logger.InfoFormat("Daemon [{0}] starting up", daemonName);
            components = new List<IBrokerComponent>();

            foreach (string file in Directory.GetFiles("Config/Triggers"))
            {
                Logger.Info("Loading triggers");
                WindsorContainer container = new WindsorContainer(new XmlInterpreter(file));
                components.AddRange(container.ResolveAll<IBrokerComponent>());
            }

            foreach (string file in Directory.GetFiles("Config/Extracters"))
            {
                Logger.Info("Loading extracters");
                WindsorContainer container = new WindsorContainer(new XmlInterpreter(file));
                components.AddRange(container.ResolveAll<IBrokerComponent>());
            }

            foreach (IBrokerComponent component in components)
            {
                Logger.InfoFormat("Starting [{0}]", component.ToString());
                component.DaemonName = daemonName;
                component.Start();
            }

            ManualTrigger manualTrigger =
                (ManualTrigger) components.Find(component => component.GetType().Equals(typeof(ManualTrigger)));

            if (manualTrigger != null)
            {
                Console.WriteLine("Enter 'quit' to close Daemon");

                while (!Console.ReadLine().Equals("QUIT", StringComparison.OrdinalIgnoreCase))
                {
                    manualTrigger.Fire();
                }
            }
            else
            {
                Console.ReadLine();    
            }
            
            Logger.Warn("Daemon closing down");
            components.ForEach(component => component.Dispose());
        }
    }
}
